package com.wnzt.baszh.util.common;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

import org.w3c.dom.Element;


public class TextMarkService {

    public static String watermark(String text, int fontSize, Font font, Color color, float alpha, File image, String imageFileName, String realUploadPath) {
            
        OutputStream os = null;
        
        try {
            Image image2 = ImageIO.read(image);
            
            int width = image2.getWidth(null);
            int height = image2.getHeight(null);
            
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            
            Graphics2D graphics2d = bufferedImage.createGraphics();
            
            graphics2d.drawImage(image2, 0, 0, width, height, null);
            
            graphics2d.setFont(font);;
            
            graphics2d.setColor(color);
            
            int width1 = fontSize * getTextLength(text);
            int height1 = fontSize;
            
            graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            
            graphics2d.rotate(Math.toRadians(10), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);
            
            int x = -width/2;
            int y = -height/2;
            
            while(x < width * 1.5) {
                y = -height/2;
                
                while(y < height * 1.5) {
                    graphics2d.drawString(text, x, y);
                    y += height1 + 80;
                }
                
                x += width1 + 80;
            }
            
            graphics2d.dispose();
            
            os = new FileOutputStream(realUploadPath + "/" + imageFileName);
            
           /* old方式
            * JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
            en.encode(bufferedImage);*/
            /**
             * author [lv tang wei] [2017年5月17日] 更换JPEG保存方式
             */
            saveAsJPEG(100, bufferedImage, (float)0.85, os);  
            
        } catch (Exception e) {
            e.printStackTrace();   
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
        
        return realUploadPath + "/" + imageFileName;
    }
    
    
    
    /**
     * 
     * @author [lv tang wei]
     * 以JPEG编码保存图片 
     * @param dpi  分辨率 
     * @param image_to_save  要处理的图像图片 
     * @param JPEGcompression  压缩比 
     * @param fos 文件输出流 
     * @throws IOException 
     * @throws IOException
     * [2017年5月17日]
     */
    public static  void saveAsJPEG(Integer dpi ,BufferedImage image_to_save, float JPEGcompression, OutputStream os) throws IOException {  
            
        //useful documentation at http://docs.oracle.com/javase/7/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html  
        //useful example program at http://johnbokma.com/java/obtaining-image-metadata.html to output JPEG data  
        
        //old jpeg class  
        //com.sun.image.codec.jpeg.JPEGImageEncoder jpegEncoder  =  com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(fos);  
        //com.sun.image.codec.jpeg.JPEGEncodeParam jpegEncodeParam  =  jpegEncoder.getDefaultJPEGEncodeParam(image_to_save);  
        
        // Image writer  
//      JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();  
        ImageWriter imageWriter  =   ImageIO.getImageWritersBySuffix("jpg").next();  
        ImageOutputStream ios  =  ImageIO.createImageOutputStream(os);  
        imageWriter.setOutput(ios);  
        //and metadata  
        IIOMetadata imageMetaData  =  imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image_to_save), null);  
           
           
        if(dpi !=  null && !dpi.equals("")){  
               
             //old metadata  
            //jpegEncodeParam.setDensityUnit(com.sun.image.codec.jpeg.JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);  
            //jpegEncodeParam.setXDensity(dpi);  
            //jpegEncodeParam.setYDensity(dpi);  
        
            //new metadata  
            Element tree  =  (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");  
            Element jfif  =  (Element)tree.getElementsByTagName("app0JFIF").item(0);  
            jfif.setAttribute("Xdensity", Integer.toString(dpi) );  
            jfif.setAttribute("Ydensity", Integer.toString(dpi));  
               
        }  
        
        
        if(JPEGcompression >= 0 && JPEGcompression <= 1f){  
        
            //old compression  
            //jpegEncodeParam.setQuality(JPEGcompression,false);  
        
            // new Compression  
            JPEGImageWriteParam jpegParams  =  (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();  
            jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);  
            jpegParams.setCompressionQuality(JPEGcompression);  
        
        }  
        
        //old write and clean  
        //jpegEncoder.encode(image_to_save, jpegEncodeParam);  
        
        //new Write and clean up  
        imageWriter.write(imageMetaData, new IIOImage(image_to_save, null, null), null);  
        ios.close();  
        imageWriter.dispose();  
        
    }  
    
    
    /**
     * 按照给定的文本内容重新生成文本长度
     * @param text
     * @return
     */
    public static int getTextLength(String text) {
        int length = text.length();
        
        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        
        length = length % 2 == 0? length / 2 : length / 2 + 1;
        return length;
    }
    
    /** 
     * 字符串转换成Color对象 
     * @param colorStr 16进制颜色字符串       如 “#cc0000”
     * @return Color对象 
     * */  
    public static Color toColorFromString(String colorStr){  
        colorStr = colorStr.substring(1);  
        Color color =  new Color(Integer.parseInt(colorStr, 16)) ;  
        return color;  
    }  
}
